#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Converts a given file into a new File with given format."""


__author__ = 'jason.stredwick@gmail.com (Jason Stredwick)'


import argparse
import os
import re
import shutil
import tempfile
from contextlib import closing


def ProcessArgs():
  parser = argparse.ArgumentParser(description='Convert file format.')
  g = parser.add_mutually_exclusive_group(required=True)
  g.add_argument('--win', dest='win', action='store_true', default=False,
                 required=False, help='Convert to Windows format.')
  g.add_argument('--unix', dest='unix', action='store_true',
                 default=False, required=False,
                 help='Convert to UNIX format.')
  parser.add_argument('--input', dest='input', action='store', default=None,
                      metavar='filename', required=True,
                      help='Input filename.')
  parser.add_argument('--output', dest='output', action='store', default=None,
                      metavar='filename', required=True,
                      help='Output filename.')
  return vars(parser.parse_args())


def Run(args):
  if not os.path.exists(args['input']):
    print '[ERROR] Missing input file. Exiting ...'
    exit()

  win = False
  if args['win']:
    win = True
    from_str = '\n'
    to_str = '\r\n'
  elif args['unix']:
    from_str = '\r\n'
    to_str = '\n'

  # Create a temporary file and fill it with the converted text.
  (tfd, tpath) = tempfile.mkstemp()
  with closing(os.fdopen(tfd, 'w')) as tout:
    with open(args['input']) as fin:
      for line in fin:
        if win:
          if re.search('[\r][\n]', line) is None:
            # Only replace \n if not already \r\n
            line = re.sub('[\n]', '\r\n', line)
        else:
          line = re.sub('[\r][\n]', '\n', line)
        tout.write(line)

  # Verify destination
  output = args['output']
  if os.path.exists(output):
    if os.path.isdir(output):
      (_, input_filename) = os.path.split(args['input'])
      output = os.path.join(output, input_filename)
    else:
      os.remove(output)

  # Move temporary file to destination.
  (output_path, output_filename) = os.path.split(output)
  if output_path and not os.path.exists(output_path):
    os.makedirs(output_path)
  shutil.move(tpath, output)


def Main():
  args = ProcessArgs()
  Run(args)


if __name__ == '__main__':
  Main()
